layui.define(['base'], function (exports) {
    var $ = layui.jquery, layer = layui.layer, $setting = layui.config, $http = layui.http, $common = layui.common;
    var $table = $('#table'), validator,
        $form = $('#myModal form'),
        $modal = $('#myModal');
    /**
     *  修改 添加 打开模态框
     */
    // 自定义
    jQuery.validator.addMethod('require-one', function (value, element) {
        return $('.require-one:checked').size() > 0;
    }, '<i class="fa fa-times-circle"></i>角色至少需要分配一个资源');
    var openModal = function (e, value, row, index) {
        $form[0].reset();
        validator = validator || $form.validate({
                ignore: '.ignore',
                groups: {
                    checks: $.map($('.require-one'), function (e, i) {
                        return $(e).attr('name')
                    }).join(' ')
                },
                rules: {
                    name: {
                        required: true
                    }
                },
                errorPlacement: function (error, element) {
                    if ($(element[0]).attr('class').indexOf('require-one') === 0) {
                        $('#resourceError').html(error);
                    } else {
                        error.insertAfter(element);
                    }
                }
            });

        //rest form
        validator.resetForm();

        //加载所有菜单
        $http.get($setting.config.resource.list, {
            pageSize: 2000
        }).send(function (obj) {
            if (obj.code == '0') {
                var menuHtml = new Array();
                $.each(obj.data, function (index, item) {
                    menuHtml.push('<div data-level="1" class="resource checkbox inline" style="width: 100%" data-id="' + item.id + '">' +
                        '<input class="require-one" type="checkbox" data-type="' + item.type + '"' +
                        ' id="check-' + item.id + '" name="check-' + item.id + '" value="' + item.id + '">' +
                        '<label for="check-' + item.id + '">' + item.text + '</label>' +
                        '</div>');
                    var pid = item.id;
                    $(item.children).each(function (index, item) {
                        menuHtml.push('<div data-level="2" class="resource checkbox inline" style="width: 100%; ' +
                            'margin-left: 20px;" data-pid="' + pid + '"  data-id="' + item.id + '">' +
                            '<input class="require-one" type="checkbox" data-type="' + item.type + '"' +
                            ' id="check-' + item.id + '" name="check-' + item.id + '" value="' + item.id + '">' +
                            '<label for="check-' + item.id + '">' + item.text + '</label>' +
                            '</div>');
                        if (item.children.length > 0) {
                            menuHtml.push('<div data-level="3" class="resource form-group col-sm-8" style="margin-left: 40px"' +
                                ' data-pid="' + item.id + '">');
                            $(item.children).each(function (index, item) {
                                menuHtml.push('<div class="checkbox inline">' +
                                    '<input class="require-one" type="checkbox" data-type="' + item.type + '"' +
                                    ' id="check-' + item.id + '" name="check-' + item.id + '" value="' + item.id + '">' +
                                    '<label for="check-' + item.id + '">' + item.text + '</label>' +
                                    '</div>');
                            });
                            menuHtml.push('</div>');
                        }
                    });

                });
                $('#resource-area').html(menuHtml.join(""));

                if (row) {  //修改    填充数据
                    $modal.data('handler', 'update');
                    $('#myModalLabel').text('修改角色');
                    $('#myModal input[name="id"]').val(row.id);
                    $('#myModal input[name="name"]').val(row.name);
                    if (row.permission) {          //填充 拥有资源
                        $(row.permission.split(',')).each(function (index, item) {
                            $('#check-' + item).attr('checked', true);
                        });
                    }
                } else {
                    $modal.data('handler', 'create');
                    $('#myModalLabel').text('添加角色');
                    $('#myModal input[name="id"]').val(0);
                }
                $modal.modal({
                    keyboard: true
                });
            }
        });
    };

    /**
     * 提交按钮
     */
    $('#submit-btn').click(function () {
        if (validator.form()) {
            $form.ajaxSubmit({
                xhrFields: {        //跨域
                    withCredentials: true
                },
                crossDomain: true,
                type: 'post',
                data: {
                    permissions: $.map($('.require-one:checked'), function (item) {
                        return $(item).val();
                    }).join(',')
                },
                url: $modal.data('handler') == 'create' ? $setting.getUri() + $setting.config.role.create : $setting.getUri() + $setting.config.role.update,
                success: function (obj) {
                    layer.msg(obj.message, {icon: obj.code == '0' ? 1 : 2});
                    if (obj.code == '0') {
                        $table.bootstrapTable('refresh');
                        $modal.modal('hide');
                    }
                }
            });
        }
    });

    // 初始化表格
    $table.bootstrapTable({
        url: $setting.getUri() + $setting.config.role.list,
        dataType: "json",
        ajaxOptions: {
            xhrFields: {        //跨域
                withCredentials: true
            },
            crossDomain: true
        },
        sidePagination: 'server',
        pagination: true,
        idField: 'id',
        dataField: 'list',
        columns: [{
            field: 'id',
            align: 'center',
            title: 'ID'
        }, {
            field: 'name',
            align: 'center',
            title: '角色名称'
        }, {
            field: 'createTime',
            align: 'center',
            title: '添加时间'
        }, {
            field: 'createUserName',
            align: 'center',
            title: '添加人'
        }, {
            field: 'viewCustomerMode',
            align: 'center',
            title: '查看用户属性'
        },{
            title: '操作',
            align: 'center',
            formatter: function (value, row) {
                if(row.id == 41 || row.id==39) {
                    return '&nbsp;&nbsp;&nbsp;<a title="修改" class="edit" data-id="' + row.userId + '" style="color:#1ab394;cursor:pointer">修改</a>';
                }
                return '&nbsp;&nbsp;&nbsp;<a title="修改" class="edit" data-id="' + row.userId + '" style="color:#1ab394;cursor:pointer">修改</a>'
                    + '&nbsp;&nbsp;&nbsp;<a title="删除" class="remove" data-id="' + row.userId + '" style="color:#1ab394;cursor:pointer">删除</a>';
            },
            events: {
                'click .edit': openModal,
                'click .remove': function (e, value, row, index) {
                    layer.confirm('确认删除此条数据吗？', {
                        icon: 2,
                        title: ['提示', 'font-size:15px;text-align:left;padding-left: 10px;'],
                        btn: ['确定', '取消'],          //按钮
                        skin: 'layui-layer-molv'
                    }, function () {
                        $http.post($setting.config.role.delete, {
                            roleId: row.id
                        }).send(function (obj) {
                            layer.msg(obj.message, {icon: obj.code == '0' ? 1 : 2});
                            if (obj.code == '0') {
                                $table.bootstrapTable('refresh');
                                $modal.modal('hide');
                            }
                        });
                    });
                }
            }
        }],
        pageSize: 20,
        pageList: [10, 20, 50, 100],
        queryParams: function (params) {
            return {
                name: $('#search').val().trim(),
                pageIndex: params.offset / params.limit + 1,
                pageSize: params.limit //页面大小
            };
        },
        responseHandler: $common.fn.table.response,
        onClickRow: function (row, $element) {
            $element.siblings().css('background-color', 'white');
            $element.css("background-color", "rgb(243, 247, 249)");
        }
    });

    $table.bootstrapTable('hideColumn', 'viewCustomerMode');
    /**
     * 权限配置 复选框选中       父级选中则子集选中。子集选中父级选中
     */
    $('#resource-area').on('click', 'input[type="checkbox"]', function () {
        var checkFlag = $(this).is(':checked'), $sel = $(this).parents('div.resource');
        var children = $sel.siblings('div[data-pid=' + $sel.attr('data-id') + ']');
        switch ($sel.attr('data-level')) {
            case '1':           //第一级菜单
                children.find('input').prop('checked', checkFlag);
                children.each(function (index, item) {
                    $sel.siblings('div[data-pid=' + $(item).attr('data-id') + ']').find('input').prop('checked', checkFlag);
                });
                break;
            case '2':           //第二级菜单
                if ($sel.siblings('div[data-pid=' + $sel.attr('data-pid') + ']').find('input:checked').length === 0) { //兄弟节点没有选中，则选中父节点
                    $sel.siblings('div[data-id=' + $sel.attr('data-pid') + ']').find('input').prop('checked', checkFlag);
                }
                children.find('input').prop('checked', checkFlag);
                break;
            case '3':           //权限点
                var p = $sel.siblings('div[data-id=' + $sel.attr('data-pid') + ']');
                if (($sel.find('input:checked').length === 0 && p.length === 0) ||
                    ($sel.find('input:checked').length === 1 && checkFlag)) {
                    //兄弟节点没有选中，则选中父节点
                    p.find('input').prop('checked', checkFlag);
                    p.each(function (index, item) {
                        $sel.siblings('div[data-id=' + $(item).attr('data-pid') + ']').find('input').prop('checked', checkFlag);
                    });
                }
                break;
        }
    });


    /**
     * 添加 按钮
     */
    $('#btn_add').on('click', openModal);


    /**
     * 查询
     */
    $('#search').keypress(function (event) {
        if (event.keyCode == 13) {
            $table.bootstrapTable('selectPage', 1);
        }
    });
    /**
     * 查询
     */
    $('.glyphicon-search').on('click', function () {
        $table.bootstrapTable('refresh');
    });
    exports('../app/admin/role', {});
});